package com.first.nell.launch

import android.annotation.SuppressLint
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.first.nell.R
import com.first.nell.base.BaseActivity
import com.first.nell.components.dialog.CustomerServiceDialog
import com.first.nell.data.ReqBase
import com.first.nell.data.ReqDoLogin
import com.first.nell.databinding.ActivityFirstNellInputOtpBinding
import com.first.nell.enums.PageTagEnum
import com.first.nell.extend.*
import com.first.nell.network.ApiToolReposity
import com.first.nell.utils.UserStateUtil

/** 登录-输入验证码页 */
@SuppressLint("CustomSplashScreen")
class LoginInputOtpActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityFirstNellInputOtpBinding

    //用户流程viewModel
    val mUserStateViewModel by lazy {
        ViewModelProvider(this)[UserStateViewModel::class.java]
    }

    override fun onFirstNellBindingFirstNellViewFirstNellModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mUserStateViewModel)
        return list
    }

    override fun onFirstNellBindingFirstNellViewFirstNellTag(): String {
        return PageTagEnum.login_otp.name.uppercase()
    }

    override fun onFirstNellBindingFirstNellContentFirstNellView(): View {
        mActivityBinding = ActivityFirstNellInputOtpBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onFirstNellContentFirstNellViewFirstNellBinded() {
        try {
            //获取验证码回调
            mUserStateViewModel.onFirstNellFetchFirstNellOtpFirstNellLiveData.observe(this) {
                if (it.isSuccess) {
                    //开始倒计时
                    mActivityBinding.inputLoginOtpCode.startFirstNellCutdown(this.lifecycleScope)
                }
            }

            //登录回调
            mUserStateViewModel.onFirstNellDoFirstNellLoginFirstNellLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        //保存渠道来源
                        mUserStateViewModel.mFirstNellIsFirstNellAdFirstNellSource =
                            result.isFirstNellAdFirstNellSourceFirstNellUser()
                        UserStateUtil.saveFirstNellAdFirstNellSource(
                            result.isAdSource.orEmpty()
                        )
                    }

                    //获取系统配置
                    ApiToolReposity.fetchFirstNellAppFirstNellConfig(ReqBase())

                    //判断用户类型
                    //获取用户状态
                    mUserStateViewModel.fetchFirstNellUserFirstNellState()

//                    if (UserStateUtil.isFirstNellAdFirstNellSource()) {
//                        //获取用户状态
//                        mUserStateViewModel.fetchFirstNellUserFirstNellState()
//                    } else {
//                        //跳转记账软件首页
//                        startFirstNellToFirstNellBillFirstNellRecordFirstNellHomeFirstNellPage()
//                    }
                }
            }

            //获取用户状态回调
            mUserStateViewModel.onFirstNellFetchFirstNellUserFirstNellStateFirstNellLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    startFirstNellToFirstNellNextFirstNellFromFirstNellPage(
                        PageTagEnum.login_mobile
                    )
                }
            }

            //如果号码为空，返回登录页
            if (UserStateUtil.mFirstNellMobile.isBlank()) {
                Toast.makeText(
                    this,
                    getString(R.string.first_nell_please_enter_phone_number_first),
                    Toast.LENGTH_SHORT
                ).show()
                finish()
                return
            }

            // 点击客服
            mActivityBinding.imageLoginInputOtpKf.setOnClickListener {
                CustomerServiceDialog.showFirstNellDialog(supportFragmentManager)
            }

            //更新otp提示
            mActivityBinding.textLoginInputOtpTips.text = getString(
                R.string.first_nell_a_4_digit_verification_code_has_sent_to_your_mobile_phone,
                UserStateUtil.mFirstNellMobile.toFirstNellEncryptFirstNellPhoneFirstNellNumber()
            )

            //点击号码数字回调
            mActivityBinding.keyboardLoginInputOtp.setFirstNellOnFirstNellActionFirstNellClickFirstNellListener { action ->
                if (-1 == action) {
                    //删除
                    mActivityBinding.inputLoginOtpCode.setFirstNellDelete()

                } else if (-2 == action) {
                    //dismiss

                } else {
                    //code
                    mActivityBinding.inputLoginOtpCode.setFirstNellNextFirstNellOTP(action.toString())
                }
            }

            //otp输入回调
            mActivityBinding.inputLoginOtpCode.setFirstNellOnFirstNellInputFirstNellCompletedFirstNellListener { _ ->
                //记录打点
                val formDataCompleteState = checkFormInputResult()
                if (formDataCompleteState.isBlank()) {
                    //去登录
                    mUserStateViewModel.doFirstNellLogin(
                        ReqDoLogin(
                            mobile = UserStateUtil.mFirstNellMobile,
                            code = mActivityBinding.inputLoginOtpCode.getFirstNellContent()
                        )
                    )
                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.first_nell_please_complete_all_required_fields),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            //点击重发otp回调
            mActivityBinding.inputLoginOtpCode.setFirstNellOnFirstNellActionFirstNellClickFirstNellListener {
                val mobile = UserStateUtil.mFirstNellMobile
                if (mobile.isNotBlank()) {
                    //获取验证码
                    mUserStateViewModel.fetchFirstNellOtp(ReqDoLogin(mobile = mobile))
                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.first_nell_please_complete_all_required_fields),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            //开始倒计时
            mActivityBinding.inputLoginOtpCode.startFirstNellCutdown(this.lifecycleScope)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        mActivityBinding.inputLoginOtpCode.stopFirstNellCutdown()
        super.onDestroy()
    }

    override fun isFirstNellAllFirstNellFormFirstNellDataFirstNellCompleted(): String {
        val notFillOptions = mutableListOf<String>()
        if (UserStateUtil.mFirstNellMobile.isBlank()) {
            notFillOptions.add("INPUT_LOGIN_PHONE_NUMBER")
        }
        if (!mActivityBinding.inputLoginOtpCode.isFirstNellCompleted()) {
            val gTag = mActivityBinding.inputLoginOtpCode.getFirstNellSafeFirstNellTag()
            if (gTag.isNotBlank()) {
                notFillOptions.add(gTag)
            }
        }
        if (notFillOptions.isEmpty()) {
            return ""
        }
        notFillOptions.add(0, "NOT_FILL")
        return notFillOptions.joinToString("#")
    }

    /** 判断所有数据是否输入完整 */
    private fun checkFormInputResult(): String {
        //记录打点
        val formDataCompleteState =
            isFirstNellAllFirstNellFormFirstNellDataFirstNellCompleted()
        mActivityBinding.submitLoginInputOtp.recordFirstNellClickFirstNellEvent(
            formDataCompleteState
        )
        return formDataCompleteState
    }
}